package beer.coder.walawala.common.gui;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import javafx.stage.StageStyle;

/**
 * TODO
 *
 * @author amath0312
 * @version 1.0
 * @date 2020-04-30 23:01
 */
public class Toast {

  private static final String DEFAULT_LABEL_STYLE = "-fx-background: rgba(56,56,56,0.7);-fx-border-radius: 25;-fx-background-radius: 15";
  private static final Color DEFAULT_TEXT_COLOR = Color.rgb(225, 255, 226);
  private static final Font DEFAULT_TEXT_FONT = new Font(16);
  private static ScheduledExecutorService service = new ScheduledThreadPoolExecutor(30);
  private Stage stage;
  private Label label;

  public static Toast make(String message) {
    return new Toast(message);
  }

  protected Toast(String message) {
    stage = new Stage();
    stage.initStyle(StageStyle.TRANSPARENT);
    label = defaultLabel(message);
    Scene scene = new Scene(label);
    //场景透明
    scene.setFill(null);

    stage.setScene(scene);
    stage.setAlwaysOnTop(true);
  }

  protected Label defaultLabel(String message) {
    Label label = new Label(message);
    label.setPrefHeight(50);
    label.setPadding(new Insets(15));
    label.setAlignment(Pos.CENTER);
    label.setStyle(DEFAULT_LABEL_STYLE);
    label.setTextFill(DEFAULT_TEXT_COLOR);
    label.setFont(DEFAULT_TEXT_FONT);
    return label;
  }

  public Toast style(String style) {
    label.setStyle(style);

    return this;
  }

  public Toast font(Color color, Font font) {
    label.setTextFill(color);
    label.setFont(font);
    return this;
  }

  public Toast message(String msg) {
    label.setText(msg);
    return this;
  }


  /**
   * 指定时间消失
   *
   * @param timeInMillis 显示时长，毫秒
   * @param parent 父窗口，可为null
   */
  public void show(long timeInMillis, Stage parent) {
    stage.initOwner(parent);
    stage.show();

    service.schedule(() -> Platform.runLater(() -> stage.close()), timeInMillis, TimeUnit.MILLISECONDS);
    if (parent != null) {
      double x = parent.getX() + (parent.getWidth() - stage.getWidth()) / 2.0;
      stage.setX(x);

      double y = parent.getY() + parent.getHeight() - 60;
      stage.setY(y);
    }
  }

}
